<?php
/**
 * LowCalVanilla Clean-up control
 *
 * @package Extensions
 * @version @@VERSION@@
 * @subpackage Low-Cal_Vanilla
 * @copyright Damien Lebrun 2007
 * @author Damien Lebrun
 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GPLv2
 */


/**
 * LowCalVanilla clean control; in case the Packer is not enable, put script that should be pack in $Head->Script.
 * @package Extensions
 * @subpackage Low-Cal_Vanilla
 */
class LowCalVanilla_CleanUp extends Control {

	/**
	 * Constructor
	 * @return void
	 * @param Context $Context
	 */
	function LowCalVanilla_CleanUp(&$Context) {
		$this->Name = 'LowCalVanilla_CleanUp';
		$this->Control($Context);;
	}

	/**
	 * Add the script to Head - with php4, it is only possible with vanilla 1.1.3+
	 * @return void
	 */
	function Render() {
		if (is_array($this->Context->PassThruVars['LOWCALVANILLA_SCRIPTS'])) {
			global $Head;
			$Head->Scripts = array_values($Head->Scripts);
			ksort($this->Context->PassThruVars['LOWCALVANILLA_SCRIPTS']);
			$PackScripts = array_values($this->Context->PassThruVars['LOWCALVANILLA_SCRIPTS']);
			foreach ($PackScripts as $key => $script) {
				$PackScripts[$key] = ConcatenatePath(
					$this->Context->Configuration['WEB_ROOT'],
					$script);
			}
			$Position = ForceInt(
				$this->Context->PassThruVars['LOWCALVANILLA_SCRIPTS_CLEANUP_POSITION'],
				null);
			if ($Position === 0){
				$Head->Scripts = array_merge($PackScripts, $Head->Scripts);
			} else if ($Position > 0 || $Position < count($Head->Scripts)) {
				$StartScript = array_slice($Head->Scripts, 0, $Position);
				$EndScript = array_slice($Head->Scripts, $Position);
				$Head->Scripts = array_merge($StartScript, $PackScripts);
				$Head->Scripts = array_merge($Head->Scripts, $EndScript);
			} else {
				$Head->Scripts = array_merge($Head->Scripts, $PackScripts);
			}
			unset($Head->Context->PassThruVars['LOWCALVANILLA_SCRIPTS']);
			unset($Head->Context->PassThruVars['LOWCALVANILLA_SCRIPTS_CLEANUP_POSITION']);
		}
	}
}